package de.wittekind.bundesjugendspiele.server.mysqlTools;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.sql.Statement;

public class MySQLSetup {

	public static void main(String[] args) {
		if (args.length >= 3) {
			String host = args[0];
			String user = args[1];
			String database = args[2];
			String password = "";
			if (args.length == 4) {
				password = args[3];
				System.out.println("Pass: " + password);
			}
			try {
				setup(host, user, password, database, true);
			} catch (SQLException | IOException e) {
				e.printStackTrace();
			}
		} else {
			System.err.println("Daten nicht übergeben");
		}
	}

	private static void setup(String host, String user, String password,
			String database, boolean samples) throws SQLException, IOException {

		String url = "jdbc:mysql://" + host + "/" + database + "?user=" + user
				+ "\u0026password=" + password;
		MySQLConnectionManager.init(url);

		Statement stmt = MySQLConnectionManager.getConnection()
				.createStatement();

		addQueries(stmt, "mysql-data/tables.sql");
		if (samples) {
			addQueries(stmt, "mysql-data/samples.sql");
		}

		stmt.executeBatch();
	}

	public static void addQueries(Statement stmt, String filename)
			throws IOException, SQLException {
		addQueries(stmt, new FileInputStream(filename));
	}

	public static void addQueries(Statement stmt, InputStream ins)
			throws IOException, SQLException {
		BufferedReader in = new BufferedReader(new InputStreamReader(ins));
		String str;
		StringBuffer sb = new StringBuffer();
		while ((str = in.readLine()) != null) {
			sb.append(str + "\n ");
		}
		String s = sb.toString();
		in.close();
		String[] sA = s.split(";");
		for (String q : sA) {

			q = q.trim();
			if (!q.isEmpty()) {
				stmt.addBatch(q);
			}
		}

	}
}
